var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var roleRouter = require('./routes/role');
var booksRouter = require('./routes/books');
var classifyRouter = require('./routes/classify');
var cartRouter = require('./routes/cart');
var orderRouter = require('./routes/order');
var order_detailsRouter = require('./routes/order_details');
var addressRouter = require('./routes/address');
var commentsRouter = require('./routes/comments');
var loopRouter = require('./routes/loop');
var productDetailRouter = require('./routes/productDetail');

var passport = require('passport')    //1.导入认证模块


var app = express();


//设置跨域请求
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header("Access-Control-Allow-Headers", "*");
  res.header('Access-Control-Allow-Methods', '*')
  next()
})


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize())      //2.使用认证模块
//3.配置认证鉴权策略
var JwtStrategy = require('passport-jwt').Strategy,
  ExtractJwt = require('passport-jwt').ExtractJwt;
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'mykey';         //和生成token时的sign函数的参数保持一致（签名）
//4.配置验证token的方法
passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
  console.log('111')
  //jwt_payload是生成token时保存的用户对象
  // User.findOne({ id: jwt_payload.sub }, function (err, user) {
  //   if (err) {
  //     return done(err, false);
  //   }
  //   if (user) {
  //     return done(null, user);
  //   } else {
  //     return done(null, false);
  //     // or you could create a new account
  //   }
  // });
  return done(null, jwt_payload);    //表示token验证通过

  //接口验证：    插在接口内部（passport需导入）
  //passport.authenticate('jwt', { session: false }),

  //前端授权：    (登录注册不需要)
  //axios.defaults.headers.common['Authorization'] =localStorage.getItem('token')
}));




app.use('/', indexRouter);
app.use('/api', userRouter);
app.use('/api', roleRouter);
app.use('/api', booksRouter);
app.use('/api', classifyRouter);
app.use('/api', cartRouter);
app.use('/api', orderRouter);
app.use('/api', order_detailsRouter);
app.use('/api', addressRouter);
app.use('/api', commentsRouter);
app.use('/api', loopRouter);
app.use('/api', productDetailRouter);



// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
